<template>
  <div class="profile-page">
    <div class="form-container">
      <h2 class="form-title">修改基本信息</h2>

      <!-- 头像展示及上传 -->
      <div class="avatar-section">
  <label class="avatar-label">
    <img :src="form.avatar || defaultAvatar" class="avatar-preview" />
    <input type="file" accept="image/*" @change="handleAvatarUpload" class="avatar-input" />
  </label>
  <span class="upload-text">点击更换头像</span>
</div>


      <form @submit.prevent="updateProfile" class="profile-form">
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="form-group-row">
            <label class="input-label">用户名</label>
            <input v-model="form.username" type="text" class="form-input">
          </div>
          <div class="form-group-row">
            <label class="input-label">昵称</label>
            <input v-model="form.nickname" type="text" class="form-input">
          </div>
          <div class="form-group-row">
            <label class="input-label">电子邮箱</label>
            <input v-model="form.email" type="email" class="form-input">
          </div>
          <div class="form-group-row">
            <label class="input-label">手机号</label>
            <input v-model="form.phone" type="text" class="form-input">
          </div>
          <div class="form-group-row">
            <label class="input-label">个人简介</label>
            <textarea v-model="form.bio" class="form-input textarea-input"></textarea>
          </div>
        </div>
        <!-- 错误提示 -->
        <div v-if="countdown > 0" class="countdown-notice">
    基本信息修改成功，{{ countdown }}秒后自动返回个人中心
  </div>
        <div class="form-group-row" v-for="(error, field) in errors" :key="field">
    <div class="error-message">{{ error[0] }}</div>
  </div>
        <!-- 提交按钮 -->
        <div class="form-actions">
          <button type="submit" :disabled="isSubmitting" class="submit-btn">
            {{ isSubmitting ? '提交中...' : '保存修改' }}
          </button>
         <button type="button" class="btn btn-go-back" @click="goBack">返回</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { useUserStore } from '@stores/userStore.js';
// 新增状态管理
const isSubmitting = ref(false);

const router = useRouter();
const store = useUserStore();
const errors = ref({});
const defaultAvatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif';
const avatarPreview = ref('');
const form = reactive({
  username: '',
  nickname: '',
  email: '',
  avatar: '',
  phone: '',
  bio: '',
});
const countdown = ref(0);// 倒计时
let countdownTimer = null;

// 获取用户数据
const fetchProfile = async () => {
  try {
    const response = await axios.get('/api/accounts/auth/user_basic_update/', { requiresAuth: true });
    Object.assign(form, response.data);
  } catch (error) {
    console.error('获取用户信息失败', error);
  }
};
// 补充头像上传处理
const handleAvatarUpload = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 预览上传的图片
  const reader = new FileReader();
  reader.onload = (e) => {
    form.avatar = e.target.result; // 直接更新为base64
    avatarPreview.value = e.target.result;
  };
  reader.readAsDataURL(file);
};

// 补充表单提交方法
const updateProfile = async () => {
  isSubmitting.value = true;
  errors.value = {};

  try {
    const formData = new FormData();

    // 先处理非文件字段
    for (const key in form) {
      if (key !== 'avatar') {
        formData.append(key, form[key]);
      }
    }

    // 单独处理头像字段（仅在修改时添加）
    if (form.avatar && form.avatar.startsWith('data:')) {
      const blob = await fetch(form.avatar).then(r => r.blob());
      formData.append('avatar', blob, 'avatar.jpg');
    }

    const response = await axios.put('/api/accounts/auth/user_basic_update/', formData, { requiresAuth: true },{
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

     countdown.value = 3;
    countdownTimer = setInterval(() => {
      countdown.value -= 1;
      if (countdown.value === 0) {
        clearInterval(countdownTimer);
        router.go(-1);
      }
    }, 1000);

  } catch (error) {
    if (error.response?.status === 400) {
      errors.value = error.response.data;
    } else {
      console.error('更新失败:', error);
    }
  } finally {
    isSubmitting.value = false;
  }
};

const goBack = async () => {
  router.go(-1);
}
onMounted(() => {
  if (!store.isLoggedIn) {
    router.push('/login');
  } else {
    fetchProfile();
  }
});
onBeforeUnmount(() => {
  if (countdownTimer) clearInterval(countdownTimer);
});
</script>


<style scoped>
.profile-page {
  min-height: 100vh;
  margin: 40px auto;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1rem;
}

.form-container {
  background: var(--profile-bg-color, #fff);
  padding: 1rem;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 600px;
  width: 100%;
}

.form-title {
  text-align: center;
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
  font-weight: bold;
  color: var(--profile-title-color);
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #ddd;
}

.avatar-input {
  display: none;
}

.upload-text {
  margin-top: 10px;
  font-size: 0.8rem;
  color: var(--profile-text-color, #7c7a7a);
  text-align: center;
}


.form-section {
  margin-bottom: 2rem;

}

.form-section h3 {
  margin-bottom: 1rem;
  font-size: 1.2rem;
  border-left: 4px solid #409eff;
  padding-left: 0.8rem;
  color: var(--profile-title-color,#333);
}

.form-group-row {
  display: flex;
  align-items: center;
  width: 80%;
  margin:15px auto;
}

.input-label {
  width: 12%;
  text-align: right;
  margin-right: 1rem;
  font-weight: 500;
  color: var(--profile-label-color,#555);
}

.form-input {
  flex-grow: 1;
  padding: 0.8rem 1rem;
  font-size: 1rem;
  border: 2px solid #ddd;
  border-radius: 5px;
  background: var(--profile-input-bg-color, #fff);
}
.form-input:focus {
  outline: none;
  border-color: var(--profile-input-focus-color, #409eff);
}

.textarea-input {
  height: 100px;
  resize: none;
}
.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 1.5rem;
}
/* 主按钮样式 */
.submit-btn {
  background: var(--profile-btn-bg-color, linear-gradient(90deg, #409eff, #66b1ff));
  color:var(--profile-btn-text-color, #fff);
  font-size: 1rem;
  padding: 0.8rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: background 0.3s, transform 0.3s ease, box-shadow 0.3s;
}

.submit-btn:hover {
  background: var(--profile-btn-hover-bg-color, linear-gradient(90deg, #66b1ff, #409eff));
  color: var(--profile-btn-text-hover-color, #fff);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}

.submit-btn:disabled {
  background: #d3d3d3;
  cursor: not-allowed;
  opacity: 0.7;
}

/* 返回按钮样式 */
.btn-go-back {
  background: var(--profile-btn-bg-color, #ffffff);;
  color:var(--profile-btn-color, #409eff);
  font-size: 1rem;
  padding: 0.8rem 1.5rem;
  border: 1px solid #409eff;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.3s, color 0.3s, transform 0.3s ease, box-shadow 0.3s;
}

.btn-go-back:hover {
  background:var(--profile-btn-hover-bg-color,#409eff);
  color: var(--profile-btn-text-hover-color, #ffffff);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
/* 新增错误提示样式 */
.error-message {
  color: #ff4d4f;
  font-size: 0.9rem;
  margin-top: 4px;
  width: 100%;
  text-align: center;
}
.countdown-notice {
  text-align: center;
  color: #67c23a;
  margin-top: 1rem;
  font-size: 0.9rem;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}
/* 优化移动端显示 */
@media (max-width: 480px) {
  .form-group-row {
    width: 95%;
    flex-direction: column;
    align-items: flex-start;
  }

  .input-label {
    width: 100%;
    text-align: left;
    margin-bottom: 0.5rem;
  }
}
</style>
